package com.hsd.whb.utils;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SecurityUtil {

    public static boolean hasManagerRole() {
        return getRole().contains("ROLE_MANAGER");
    }

    public static boolean hasRecorderRole() {
        return getRole().contains("ROLE_RECORDER");
    }

    public static boolean hasRootRole() {
        return getRole().contains("ROLE_ROOT");
    }

    public static List<String> getRole() {
        Authentication authentication = getAuthentication();
        Iterator iterator = authentication.getAuthorities().iterator();
        List<String> list = new ArrayList<>();
        while (iterator.hasNext()) {
            SimpleGrantedAuthority simpleGrantedAuthority = (SimpleGrantedAuthority) iterator.next();
            list.add(simpleGrantedAuthority.getAuthority());
        }
        return list;
    }

    public static String getUsername() {
        Authentication authentication = getAuthentication();
        return authentication.getName();
    }

    private static Authentication getAuthentication() {
        SecurityContext context = SecurityContextHolder.getContext();
        return context.getAuthentication();
    }

}
